﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace _ReservationApp
{
    public partial class Form1 : Form
    {
        // 从配置文件中读取 URL
        static string apiUrl = ConfigurationManager.AppSettings["ApiUrl"];
        static string NewapiUrl = ConfigurationManager.AppSettings["NewApiUrl"];
        static List<string> macs = new List<string>();
        public Form1()
        {
            InitializeComponent();
            InitLog();
            GetMAC();
        }

        private void GetMAC()
        {
            // 获取所有网络接口
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            // 过滤出物理网卡（以太网或无线网卡）
            var physicalNetworkInterfaces = networkInterfaces
                .Where(n => n.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                            n.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                .ToList();

            if (physicalNetworkInterfaces.Any())
            {
                // 获取第一个物理网卡的MAC地址
                PhysicalAddress physicalAddress = physicalNetworkInterfaces.First().GetPhysicalAddress();
                if (physicalAddress != null && physicalAddress.GetAddressBytes().Length > 0)
                {
                    // 将MAC地址格式化为常见的十六进制字符串
                    string macAddress = string.Join(":", physicalAddress.GetAddressBytes().Select(b => b.ToString("X2")));
                    Console.WriteLine($"MAC Address: {macAddress}");
                    macs.Add(macAddress);
                }
                else
                {
                    Console.WriteLine("No MAC address found for the physical network interface.");
                }
            }
            else
            {
                Console.WriteLine("No physical network interfaces found.");
            }
        }
        private async void reservation_Click(object sender, EventArgs e)
        {
            this.reservation.Enabled = false;
            Log("开始预约...");

            UserCredentials userCredentials = null;
            UserCredentialsDto userCredentialsdto = null;
            List<UserCredentialsDto> list = new List<UserCredentialsDto>();
            if (isNew.Checked)
            {
                string filePath = "AccountInfo.txt"; // 文件路径

                try
                {
                    using (StreamReader reader = new StreamReader(filePath))
                    {
                        string line;
                        while ((line = reader.ReadLine().Replace("\r", "").Replace("\n", "")) != null && line != "") // 逐行读取
                        {
                            var strs = line.Split('-');
                            if (strs.Length > 0)
                            {
                                userCredentialsdto = new UserCredentialsDto
                                {
                                    username = strs[0],
                                    password = strs[1],
                                    date = strs[3],
                                    phone = strs[2],
                                    isenablestartdate = checkBoxtime.Checked ? "1" : "0",
                                    startdate = textBoxtime.Text.Trim()
                                };
                                list.Add(userCredentialsdto);
                            }
                        }
                    }

                    var body = await ReservationListAPIAsync(list);
                    Log(body);
                    Log("请1分钟后查看预约状态...");
                }
                catch (FileNotFoundException)
                {
                    MessageBox.Show("文件未找到！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
            else
            {
                if (!isConfig.Checked)
                {

                    var Username = usernumber.Text.Trim();
                    var Password = password.Text.Trim();
                    var Date = date.Text.Trim();
                    var Phone = phone.Text.Trim();
                    if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Date) || string.IsNullOrEmpty(Phone))
                    {
                        MessageBox.Show("输入框都是必填项!");
                        return;
                    }
                    // 创建用户凭证对象
                    userCredentials = new UserCredentials
                    {
                        username = Username,
                        password = Password,
                        date = Date,
                        phone = Phone,
                        logName = Guid.NewGuid().ToString(),
                        isenablestartdate = checkBoxtime.Checked ? "1" : "0",
                        startdate = textBoxtime.Text.Trim()
                    };

                    var body = await ReservationAPIAsync(userCredentials);
                    Log(body);
                }
                else
                {
                    string filePath = "AccountInfo.txt"; // 文件路径

                    try
                    {
                        using (StreamReader reader = new StreamReader(filePath))
                        {
                            string line;
                            while ((line = reader.ReadLine().Replace("\r", "").Replace("\n", "")) != null && line != "") // 逐行读取
                            {
                                var strs = line.Split('-');
                                if (strs.Length > 0)
                                {
                                    userCredentials = new UserCredentials
                                    {
                                        username = strs[0],
                                        password = strs[1],
                                        date = strs[3],
                                        phone = strs[2],
                                        logName = Guid.NewGuid().ToString(),
                                        isenablestartdate = checkBoxtime.Checked ? "1" : "0",
                                        startdate = textBoxtime.Text.Trim()
                                    };

                                    var body = await ReservationAPIAsync(userCredentials);
                                    Log($"{strs[0]}--预约中...");
                                    Log(body);
                                    Log("请1分钟后查看预约状态...");
                                }
                                Thread.Sleep(200);
                            }
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        MessageBox.Show("文件未找到！");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"发生错误: {ex.Message}");
                    }
                }
            }



            Log("预约中...");
            Log("请1分钟后查看预约状态...");
            this.reservation.Enabled = true;
        }



        private async Task<string> ReservationAPIAsync(UserCredentials userCredentials)
        {
            // 将对象序列化为 JSON 字符串
            string jsonContent = JsonConvert.SerializeObject(userCredentials);

            // 创建 StringContent
            var requestContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, apiUrl + "api/start");
            request.Content = requestContent;
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            // 添加 MAC 地址到请求头
            request.Headers.Add("X-MAC-Address", macs[0]);
            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }

        private async Task<string> ReservationListAPIAsync(List<UserCredentialsDto> listDto)
        {
            // 将对象序列化为 JSON 字符串
            string jsonContent = JsonConvert.SerializeObject(listDto);

            // 创建 StringContent
            var requestContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, NewapiUrl + "api/Reservation");
            request.Content = requestContent;
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            // 添加 MAC 地址到请求头
            request.Headers.Add("X-MAC-Address", macs[0]);
            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }


        #region 日志

        public void InitLog()
        {
            // 设置一些初始属性
            richTextBoxLogs.ReadOnly = true;
            richTextBoxLogs.ScrollBars = RichTextBoxScrollBars.Vertical;
            richTextBoxLogs.WordWrap = true;
            richTextBoxLogs.Font = new System.Drawing.Font("Consolas", 10);
        }
        public void Log(string message, Color color = default)
        {
            if (color == default)
            {
                color = SystemColors.WindowText; // 默认颜色
            }

            if (richTextBoxLogs.InvokeRequired)
            {
                // 添加日志消息
                richTextBoxLogs.Invoke(new Action(() =>
               {
                   AppendTextWithColor(message + "." + Environment.NewLine, color);
               }));

            }
            else
            {
                AppendTextWithColor(message + "." + Environment.NewLine, color);
            }


            // 滚动到底部
            richTextBoxLogs.ScrollToCaret();
        }

        public void AppendTextWithColor(string text, Color color)
        {
            //if (color == Color.Red)
            //{
            //    await LogService.Instance.WriteErrorLog(text);
            //}
            //else
            //{
            //    await LogService.Instance.WriteInfoLog(text);
            //}
            // 保存当前选择位置
            int start = richTextBoxLogs.TextLength;
            richTextBoxLogs.AppendText($"{DateTime.Now} {text}");
            int end = richTextBoxLogs.TextLength;

            // 设置选中的文本颜色
            richTextBoxLogs.Select(start, end - start);
            richTextBoxLogs.SelectionColor = color;
            richTextBoxLogs.SelectionLength = 0; // 取消选中
        }
        #endregion

        private void isConfig_CheckedChanged(object sender, EventArgs e)
        {
            if (isConfig.Checked)
            {
                usernumber.Text = ""; usernumber.ReadOnly = true;
                password.Text = ""; password.ReadOnly = true;
                date.Text = ""; date.ReadOnly = true;
                phone.Text = ""; phone.ReadOnly = true;

            }
            else
            {
                usernumber.Text = ""; usernumber.ReadOnly = false;
                password.Text = ""; password.ReadOnly = false;
                date.Text = ""; date.ReadOnly = false;
                phone.Text = ""; phone.ReadOnly = false;
            }
        }

        private void showlog_Click(object sender, EventArgs e)
        {

        }

        private void checkIsNine_CheckedChanged(object sender, EventArgs e)
        {
            if (checkIsNine.Checked)
            {
                textBoxtime.Text = "08:59:58";
            }
            else
            {
                textBoxtime.Text = "09:59:58";
            }
        }
    }

    public class UserCredentials
    {
        public string username { get; set; }
        public string password { get; set; }
        public string date { get; set; }
        public string phone { get; set; }
        public string logName { get; set; }
        public string startdate { get; set; }
        public string isenablestartdate { get; set; }
        public string isBS { get; set; }
    }

    public class UserCredentialsDto
    {
        public string username { get; set; }
        public string password { get; set; }
        public string date { get; set; }
        public string phone { get; set; }
        public string startdate { get; set; }
        public string isenablestartdate { get; set; }
    }
}
